package com.sanxia.market.service.hongbao;


import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.sanxia.common.enums.CodesEnum;
import com.sanxia.common.utils.CreateNo;
import com.sanxia.common.utils.CreateSignUtil;
import com.sanxia.common.utils.JsonUtil;
import com.sanxia.common.utils.MD5Util;
import com.sanxia.common.utils.StringUtil;
import com.sanxia.common.utils.WXHttpClient;
import com.sanxia.common.utils.XmlParse;
import com.sanxia.market.entity.CommandWord;
import com.sanxia.market.entity.HongbaoLog;
import com.sanxia.market.entity.User;
import com.sanxia.market.entity.UserShareLog;
import com.sanxia.market.entity.WxHongbaoInfo;
import com.sanxia.market.entity.WxInfo;
import com.sanxia.market.service.CommandWordService;
import com.sanxia.market.service.HongbaoLogService;
import com.sanxia.market.service.UserService;
import com.sanxia.market.service.UserShareLogService;
import com.sanxia.market.service.WxHongbaoInfoService;
import com.sanxia.market.service.WxInfoService;




 /**
* @Title: HongbaoLogService.java
* @Package com.sanxia.market.service
* @Description:
* @author 赵贯男
* @date 2019-01-18 13:33:52
* @version V1.0
* create by codeFactory
*/
@Service("HongbaoService")
public class HongbaoService {

	@Autowired
	private WxInfoService wxInfoService;

	@Autowired
	private WxHongbaoInfoService wxHongbaoInfoService;

	@Autowired
	private UserService userService;

	@Autowired
	private HongbaoLogService hongbaoLogService;

	@Autowired
	private UserShareLogService  userShareLogService;
	
	@Autowired
	private CommandWordService commandWordService;
	
	@Autowired
	private UserService baseUserPlusMapper;

	@Autowired
	private UserShareLogService  cultureUserShareLogPlusMapper;

	public Map<String, String> userExamSubmit(String openid, Integer score, String name, String mobile, String address) {
		// TODO Auto-generated method stub
		Map<String, String> restmap=new HashMap<String,String>();
		if(StringUtils.isEmpty(openid)) {
			restmap.put("code", "0002");
			restmap.put("msg", "openid不能为空");
			return restmap;
		}
		String mchid = "2";
		Map<String,Object> paramMap=new HashMap<String,Object>();
		paramMap.put("userOpenid", openid);
		paramMap.put("mechId", mchid);
		User user=userService.getBy(paramMap);
		if(!StringUtil.isEmpty(user)) {
			if("1".equals(user.getIsSubmit())) {
				restmap.put("code", "0001");
				restmap.put("msg", "已经交卷过了");
				return restmap;
			}
			user.setIsSubmit("1");
			user.setTureName(name);
			user.setUserPhone(mobile);
			user.setUserAddress(address);
			user.setSubmissionTime(new Date());
			user.setUserAnswerScore(score+"");
			userService.updateOne(user);
			
			restmap.put("code", "0000");
			restmap.put("msg", "交卷成功");
			return restmap;
		}

		restmap.put("code", CodesEnum.FAIL0004.getCode());
		restmap.put("msg", CodesEnum.FAIL0004.getMsg());
		return restmap;
	}
	
	public Map<String, String> userInfo(String mchid, String openid) throws IOException {
		Map<String, String> restmap=new HashMap<String,String>();
		Map<String,Object> paramMap=new HashMap<String,Object>();
		paramMap.put("userOpenid", openid);
		paramMap.put("mechId", mchid);
		User user=userService.getBy(paramMap);
		if(user==null) {
			restmap.put("code", "0002");
			restmap.put("msg", "用户不存在。");
			return restmap;
		}
		//是否领过红包
		if("1".equals(user.getUserType())) {
			restmap.put("useRedPacket", "1");
		}else {
			restmap.put("useRedPacket", "0");
		}
		//是否已经交卷
		if("1".equals(user.getIsSubmit())) {
			restmap.put("userSubmit", "1");
		}else {
			restmap.put("userSubmit", "0");
		}
		//点击领红包金额
		paramMap.clear();
		paramMap.put("hongbaoType", "National");
		WxHongbaoInfo wxHongbaoInfo=wxHongbaoInfoService.getBy(paramMap);
		String totalAmount = wxHongbaoInfo.getTotalAmount();
		BigDecimal divide = new BigDecimal(totalAmount).divide(new BigDecimal("100")).setScale(1,BigDecimal.ROUND_FLOOR);
		restmap.put("totalAmount", divide+"");
		
		//分享返佣领红包金额
//		paramMap.clear();
//		paramMap.put("hongbaoType", "Recommend");
//		wxHongbaoInfo=wxHongbaoInfoService.getBy(paramMap);
//		String recommendTotalAmount = wxHongbaoInfo.getTotalAmount();
//		restmap.put("recommendTotalAmount", recommendTotalAmount);
		
		paramMap.clear();
		paramMap.put("userId", user.getId()+"");
		List<UserShareLog> list = userShareLogService.listBy(paramMap);
		if(CollectionUtils.isNotEmpty(list)) {
			restmap.put("busId", list.get(0).getId()+"");
		}
		
		return restmap;
	}
	
	public Map<String, String> sendhongbao(String mchid, String openid) throws IOException {
		Map<String, String> restmap=new HashMap<String,String>();
		Map<String,Object> paramMap=new HashMap<String,Object>();
		paramMap.put("userOpenid", openid);
		paramMap.put("mechId", mchid);
		User user=userService.getBy(paramMap);
		if(!StringUtil.isEmpty(user)&&"1".equals(user.getUserType())) {
			restmap.put("code", CodesEnum.FAIL0007.getCode());
			restmap.put("msg", "用户已领取！");
			return restmap;
		}


		paramMap.clear();
		paramMap.put("mchId", mchid);
		WxInfo	wxInfo=wxInfoService.getBy(paramMap);
		paramMap.clear();
		paramMap.put("hongbaoType", "National");
		WxHongbaoInfo wxHongbaoInfo=wxHongbaoInfoService.getBy(paramMap);
		Date begin_time=wxHongbaoInfo.getBeginTime();
		Date end_time=wxHongbaoInfo.getEndTime();
		Date now=new Date();
		if(now.before(begin_time)) {
			restmap.put("code", CodesEnum.FAIL0103.getCode());
			restmap.put("msg", CodesEnum.FAIL0103.getMsg());
			return restmap;
		}
		if(now.after(end_time)) {
			restmap.put("code", CodesEnum.FAIL0102.getCode());
			restmap.put("msg", CodesEnum.FAIL0102.getMsg());
			return restmap;
		}
		String  url=wxHongbaoInfo.getUrl();
		String wx_appid=wxInfo.getWxAppid();
		String wx_mchid=wxInfo.getWxMchId();
		String wx_mchkey=wxInfo.getWxMchKey();
		String wxCertPath=wxInfo.getWxCertPath();
//		String wxCertPath="E:/cert/apiclient_cert.p12";
		String logNo=CreateNo.cerateNo(user.getId()+"");
		//发送微信红包
		SortedMap<String,Object> map =new TreeMap<String,Object>();
		map.put("nonce_str", "ASDXCV");
		map.put("mch_billno", logNo);
		map.put("mch_id", wx_mchid);
		map.put("wxappid", wx_appid);
		map.put("send_name", wxHongbaoInfo.getMchName());
		map.put("re_openid", openid);
		map.put("total_amount", wxHongbaoInfo.getTotalAmount());
		map.put("total_num", "1");
		map.put("wishing", wxHongbaoInfo.getWishing());
		map.put("client_ip", "127.0.0.1");
		map.put("act_name", wxHongbaoInfo.getActName());
		map.put("remark", wxHongbaoInfo.getRemark());
		map.put("scene_id", "PRODUCT_1");
		String sign=CreateSignUtil.createSignBalance("utf-8", map, wx_mchkey);
		map.put("sign", sign);
		String rest=WXHttpClient.postData(url, XmlParse.mapToXml(map, "xml"), wx_mchid, wxCertPath);
		System.out.println("http请求结果:"+rest);
		Map<String,Object> requestmap=JsonUtil.jsonStr2Map(XmlParse.xml2JSON(rest));
		String return_code=(String)((Map)requestmap.get("xml")).get("return_code");
		String return_msg=(String) ((Map)requestmap.get("xml")).get("return_msg");
		String result_code=(String) ((Map)requestmap.get("xml")).get("result_code");
		System.out.println("return_code="+return_code);
		System.out.println("result_code="+result_code);
		if("SUCCESS".equals(return_code)&&"SUCCESS".equals(result_code)) {
			HongbaoLog hongbaoLog=new HongbaoLog();
			hongbaoLog.setLogNo(logNo);
			hongbaoLog.setLogStatus("1");
			hongbaoLog.setMchId(mchid);
			hongbaoLog.setSendListid((String)((Map)requestmap.get("xml")).get("send_listid")+"");
			hongbaoLog.setTotalAmount(Integer.valueOf((String)((Map)requestmap.get("xml")).get("total_amount")+"") );
			hongbaoLog.setUserId(user.getId());
			hongbaoLog.setUserOpenid(openid);	
			hongbaoLog.setAddTime(new Date());
			hongbaoLog.setHongbaoType("1");
			hongbaoLogService.insertOne(hongbaoLog);
			user.setUserType("1");
			userService.updateOne(user);
			
			//给父级返红包逻辑
			giveParentRedPacket(mchid,openid);

			restmap.put("code", CodesEnum.SUCCESS.getCode());
			restmap.put("msg", CodesEnum.SUCCESS.getMsg());
			return restmap;
		}else {
			HongbaoLog hongbaoLog=new HongbaoLog();
			hongbaoLog.setLogNo(logNo);
			hongbaoLog.setLogStatus("0");
			hongbaoLog.setMchId(mchid);
			hongbaoLog.setUserId(user.getId());
			hongbaoLog.setUserOpenid(openid);
			hongbaoLog.setLogDesc(rest);
			hongbaoLog.setAddTime(new Date());
			user.setUserType("1");
			hongbaoLog.setHongbaoType("1");
			hongbaoLogService.insertOne(hongbaoLog);
			if("帐号余额不足，请到商户平台充值后再重试".equals(return_msg)) {
				restmap.put("code", CodesEnum.FAIL0102.getCode());
				restmap.put("msg", CodesEnum.FAIL0102.getMsg());
			}else {

			restmap.put("code", CodesEnum.FAIL0004.getCode());
			restmap.put("msg", "哎呀，红包滑走了，请稍后再试");
			}
			return restmap;
		}
	}
	
	
	public void giveParentRedPacket(String mchid,String openid) throws IOException  {
		Map<String,Object> paramMap=new HashMap<String,Object>();
		
		paramMap.put("userOpenid", openid);
		paramMap.put("mechId", mchid);
		User user=userService.getBy(paramMap);
		//用户不存在或当期用户没有父级则不返佣
		if(user==null||org.apache.commons.lang.StringUtils.isEmpty(user.getParentUserId())||Integer.parseInt(user.getParentUserId())<=0) {
			System.out.println("用户不存在或当期用户没有父级则不返佣");
			return;
		}
		User parentUser = userService.getById(user.getParentUserId());
		//用户不存在或当期用户没有父级则不返佣
		if(parentUser==null) {
			System.out.println("用户不存在或当期用户没有父级则不返佣");
			return;
		}
		
		if(user.getId().intValue()==parentUser.getId().intValue()) {
			System.out.println("父级别用户和自己用户一样则不返佣");
			return;
		}
		
		paramMap.clear();
		paramMap.put("mchId", mchid);
		WxInfo	wxInfo=wxInfoService.getBy(paramMap);
		paramMap.clear();
		paramMap.put("hongbaoType", "Recommend");
		WxHongbaoInfo wxHongbaoInfo=wxHongbaoInfoService.getBy(paramMap);

		String  url=wxHongbaoInfo.getUrl();
		String wx_appid=wxInfo.getWxAppid();
		String wx_mchid=wxInfo.getWxMchId();
		String wx_mchkey=wxInfo.getWxMchKey();
		String wxCertPath=wxInfo.getWxCertPath();
		String logNo=CreateNo.cerateNo(user.getId()+"");
		//发送微信红包
		SortedMap<String,Object> map =new TreeMap<String,Object>();
		map.put("nonce_str", "ASDXCV");
		map.put("mch_billno", logNo);
		map.put("mch_id", wx_mchid);
		map.put("wxappid", wx_appid);
		map.put("send_name", wxHongbaoInfo.getMchName());
		map.put("re_openid", parentUser.getUserOpenid());
		map.put("total_amount", wxHongbaoInfo.getTotalAmount());
		map.put("total_num", "1");
		map.put("wishing", wxHongbaoInfo.getWishing());
		map.put("client_ip", "127.0.0.1");
		map.put("act_name", wxHongbaoInfo.getActName());
		map.put("remark", wxHongbaoInfo.getRemark());
		map.put("scene_id", "PRODUCT_1");
		String sign=CreateSignUtil.createSignBalance("utf-8", map, wx_mchkey);
		map.put("sign", sign);
		String rest=WXHttpClient.postData(url, XmlParse.mapToXml(map, "xml"), wx_mchid, wxCertPath);
		System.out.println("http请求结果:"+rest);
		Map<String,Object> requestmap=JsonUtil.jsonStr2Map(XmlParse.xml2JSON(rest));
		String return_code=(String)((Map)requestmap.get("xml")).get("return_code");
		String return_msg=(String) ((Map)requestmap.get("xml")).get("return_msg");
		String result_code=(String) ((Map)requestmap.get("xml")).get("result_code");
		System.out.println("return_code="+return_code);
		System.out.println("result_code="+result_code);
		if("SUCCESS".equals(return_code)&&"SUCCESS".equals(result_code)) {
			HongbaoLog hongbaoLog=new HongbaoLog();
			hongbaoLog.setLogNo(logNo);
			hongbaoLog.setLogStatus("1");
			hongbaoLog.setMchId(mchid);
			hongbaoLog.setSendListid((String)((Map)requestmap.get("xml")).get("send_listid")+"");
			hongbaoLog.setTotalAmount(Integer.valueOf((String)((Map)requestmap.get("xml")).get("total_amount")+"") );
			hongbaoLog.setUserId(user.getId());
			hongbaoLog.setUserOpenid(openid);	
			hongbaoLog.setAddTime(new Date());
			hongbaoLog.setHongbaoType("2");
			hongbaoLogService.insertOne(hongbaoLog);
			user.setUserType("1");
			userService.updateOne(user);

			return ;
		}else {
			HongbaoLog hongbaoLog=new HongbaoLog();
			hongbaoLog.setLogNo(logNo);
			hongbaoLog.setLogStatus("0");
			hongbaoLog.setMchId(mchid);
			hongbaoLog.setUserId(user.getId());
			hongbaoLog.setUserOpenid(openid);
			hongbaoLog.setLogDesc(rest);
			hongbaoLog.setAddTime(new Date());
			hongbaoLogService.insertOne(hongbaoLog);
			
			return ;
		}
	}

//	public static void main(String[] args) throws IOException {
//		String  url="https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
//		String key="beijingsanxiayun20170801dongdong";
//		SortedMap<String,Object> map =new TreeMap<String,Object>();
//		map.put("nonce_str", "ASDXCV");
//		map.put("mch_billno", "123455");
//		map.put("mch_id", "1486282192");
//		map.put("wxappid", "wxd4cf1e0e04c01d66");
//		map.put("send_name", "三夏科技");
//		map.put("re_openid", "oUBwWxMS3K4SaJxvsUdGNiMClLF0");
//		map.put("total_amount", "88");
//		map.put("total_num", "1");
//		map.put("wishing", "三夏给您拜年啦！");
//		map.put("client_ip", "127.0.0.1");
//		map.put("act_name", "拜年红包");
//		map.put("remark", "三夏全员拜年");
//		map.put("scene_id", "PRODUCT_1");
//		String sign=CreateSignUtil.createSignBalance("utf-8", map, key);
//		map.put("sign", sign);
//		String rest=WXHttpClient.postData(url, XmlParse.mapToXml(map, "xml"), "1486282192", "C:\\Users\\zgn\\Desktop\\1486282192_20190118_cert\\apiclient_cert.p12");
//
//		System.out.println(rest);
//
//
//	}

	public Map<String, String> command_word(String mchid, String openid, String command_word) throws IOException {
		Map<String, String> restmap=new HashMap<String,String>();
		Map<String,Object> paramMap=new HashMap<String,Object>();
		paramMap.put("userOpenid", openid);
		paramMap.put("mechId", mchid);
		User user=userService.getBy(paramMap);
		if(!StringUtil.isEmpty(user)&&"1".equals(user.getUserType())) {
			restmap.put("code", CodesEnum.FAIL0007.getCode());
			restmap.put("msg", "用户已领取！");
			return restmap;
		}


		paramMap.clear();
		paramMap.put("mchId", mchid);
		WxInfo	wxInfo=wxInfoService.getBy(paramMap);
		paramMap.clear();
		paramMap.put("hongbaoType", "Command");
		WxHongbaoInfo wxHongbaoInfo=wxHongbaoInfoService.getBy(paramMap);
		Date begin_time=wxHongbaoInfo.getBeginTime();
		Date end_time=wxHongbaoInfo.getEndTime();
		Date now=new Date();
		if(now.before(begin_time)) {
			restmap.put("code", CodesEnum.FAIL0103.getCode());
			restmap.put("msg", CodesEnum.FAIL0103.getMsg());
			return restmap;
		}
		if(now.after(end_time)) {
			restmap.put("code", CodesEnum.FAIL0102.getCode());
			restmap.put("msg", CodesEnum.FAIL0102.getMsg());
			return restmap;
		}
		//校验口令
		paramMap.clear();
		paramMap.put("wxHongbaoInfoId", wxHongbaoInfo.getId());
		List<CommandWord> commandWordlist=commandWordService.listBy(paramMap);
		if(StringUtil.isEmpty(commandWordlist)) {
			restmap.put("code", CodesEnum.FAIL0001.getCode());
			restmap.put("msg", CodesEnum.FAIL0001.getMsg());
			return restmap;
		}
		String commandWord_id="";
		/**
		 * begin此处将来可以抽出为单独的口令校验方法  入参：commandWordlist，command_word。出参 commandWord_id
		 */
		for (int i = 0; i < commandWordlist.size(); i++) {
			CommandWord commandWord=commandWordlist.get(i);
			String command_type=commandWord.getCommandType();
			long give_number= commandWord.getGiveNumber();
			String command_word_mi=commandWord.getCommandWord();
			String question=commandWord.getQuestion();
			String key=commandWord.getCommandKey();

			if(give_number<1) {
				restmap.put("code", CodesEnum.FAIL0102.getCode());
				restmap.put("msg", CodesEnum.FAIL0102.getMsg());
				return restmap;
			}
			if("pass".equals(command_type)) {//口令类型（pass只需要口令，ques需要口令和问题）
				StringBuffer sb = new StringBuffer();
				sb.append(command_word_mi).append(key).append(openid);
				String sign=MD5Util.MD5Encode(sb.toString(), "UTF-8").toUpperCase();
				System.out.println("sign="+sign);
				System.out.println("command_word="+command_word);
				if(sign.equals(command_word)) {//此处写法口令必须唯一
					commandWord_id=commandWord.getId()+"";
				}
			}
			if("ques".equals(command_type)) {//口令类型（pass只需要口令，ques需要口令和问题）
				StringBuffer sb = new StringBuffer();
				sb.append(command_word_mi).append(key).append(openid).append(question);//****
				String sign=MD5Util.MD5Encode(sb.toString(), "UTF-8").toUpperCase();
				if(sign.equals(command_word)) {//此处写法口令必须唯一
					commandWord_id=commandWord.getId()+"";
				}
			}
		}

		if(StringUtil.isEmpty(commandWord_id)) {
		restmap.put("code", CodesEnum.FAIL0008.getCode());
		restmap.put("msg", CodesEnum.FAIL0008.getMsg());
		return restmap;
		}
		/**
		 * end此处包裹将来可以抽出为单独的口令校验方法  入参：commandWordlist，command_word。出参 commandWord_id
		 */
		//发送微信红包
		String  url=wxHongbaoInfo.getUrl();
		String wx_appid=wxInfo.getWxAppid();
		String wx_mchid=wxInfo.getWxMchId();
		String wx_mchkey=wxInfo.getWxMchKey();
		String wxCertPath=wxInfo.getWxCertPath();
		String logNo=CreateNo.cerateNo(user.getId()+"");

		SortedMap<String,Object> map =new TreeMap<String,Object>();
		map.put("nonce_str", "ASDXCV");
		map.put("mch_billno", logNo);
		map.put("mch_id", wx_mchid);
		map.put("wxappid", wx_appid);
		map.put("send_name", wxHongbaoInfo.getMchName());
		map.put("re_openid", openid);
		map.put("total_amount", wxHongbaoInfo.getTotalAmount());
		map.put("total_num", "1");
		map.put("wishing", wxHongbaoInfo.getWishing());
		map.put("client_ip", "127.0.0.1");
		map.put("act_name", wxHongbaoInfo.getActName());
		map.put("remark", wxHongbaoInfo.getRemark());
		map.put("scene_id", "PRODUCT_4");
		String sign=CreateSignUtil.createSignBalance("utf-8", map, wx_mchkey);
		map.put("sign", sign);
		String rest=WXHttpClient.postData(url, XmlParse.mapToXml(map, "xml"), wx_mchid, wxCertPath);
		System.out.println("http请求结果:"+rest);
		Map<String,Object> requestmap=JsonUtil.jsonStr2Map(XmlParse.xml2JSON(rest));
		String return_code=(String)((Map)requestmap.get("xml")).get("return_code");
		String return_msg=(String) ((Map)requestmap.get("xml")).get("return_msg");
		String result_code=(String) ((Map)requestmap.get("xml")).get("result_code");
		System.out.println("return_code="+return_code);
		System.out.println("result_code="+result_code);
		if("SUCCESS".equals(return_code)&&"SUCCESS".equals(result_code)) {
			HongbaoLog hongbaoLog=new HongbaoLog();
			hongbaoLog.setLogNo(logNo);
			hongbaoLog.setLogStatus("1");
			hongbaoLog.setMchId(mchid);
			hongbaoLog.setSendListid((String)((Map)requestmap.get("xml")).get("send_listid")+"");
			hongbaoLog.setTotalAmount(Integer.valueOf((String)((Map)requestmap.get("xml")).get("total_amount")+"") );
			hongbaoLog.setUserId(user.getId());
			hongbaoLog.setUserOpenid(openid);
			hongbaoLog.setAddTime(new Date());
			hongbaoLogService.insertOne(hongbaoLog);
			user.setUserType("1");
			userService.updateOne(user);

			CommandWord	commandWord=commandWordService.getById(commandWord_id);
			commandWord.setGiveNumber(commandWord.getGiveNumber()-1L);
			commandWordService.updateOne(commandWord);

			restmap.put("code", CodesEnum.SUCCESS.getCode());
			restmap.put("msg", CodesEnum.SUCCESS.getMsg());
			return restmap;
		}else {
			HongbaoLog hongbaoLog=new HongbaoLog();
			hongbaoLog.setLogNo(logNo);
			hongbaoLog.setLogStatus("0");
			hongbaoLog.setMchId(mchid);
			hongbaoLog.setUserId(user.getId());
			hongbaoLog.setUserOpenid(openid);
			hongbaoLog.setLogDesc(rest);
			hongbaoLog.setAddTime(new Date());
			hongbaoLogService.insertOne(hongbaoLog);
			if("帐号余额不足，请到商户平台充值后再重试".equals(return_msg)) {
				restmap.put("code", CodesEnum.FAIL0102.getCode());
				restmap.put("msg", CodesEnum.FAIL0102.getMsg());
			}else {

			restmap.put("code", CodesEnum.FAIL0004.getCode());
			restmap.put("msg", CodesEnum.FAIL0004.getMsg());
			}
			return restmap;
		}
	}


	public static void main (String[] args) throws IOException{
		String  url="https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
		String wx_appid="wx1be1cc389e8dffb9";
		String wx_mchid="1555527911";
		String wx_mchkey="Thwj8888Thwj8888Thwj8888Thwj8888";
		String wxCertPath="E:/cert/apiclient_cert.p12";
		String logNo=CreateNo.cerateNo(12334+"");

		SortedMap<String,Object> map =new TreeMap<String,Object>();
		map.put("nonce_str", "ASDXCV");
		map.put("mch_billno", logNo);
		map.put("mch_id", wx_mchid);
		map.put("wxappid", wx_appid);
		map.put("send_name", "测试红包");
		map.put("re_openid", "oKvRh5ljcxtQeW4GcgYz7DOa1_5U");//"oKvRh5oB_kWkH1NrgfXnszBisrLM");
		map.put("total_amount", 30);
		map.put("total_num", "1");
		map.put("wishing", "祝福红包");
		map.put("client_ip", "127.0.0.1");
		map.put("act_name", "祝福红包二");
		map.put("remark", "祝福红包描述");
		map.put("scene_id", "PRODUCT_1");
		String sign=CreateSignUtil.createSignBalance("utf-8", map, wx_mchkey);
		map.put("sign", sign);
		String rest=WXHttpClient.postData(url, XmlParse.mapToXml(map, "xml"), wx_mchid, wxCertPath);
		System.out.println("http请求结果:"+rest);
	}

	public Map<String, Object> getOpenidByCode(String code,String state) {
			// TODO Auto-generated method stub
		try {
			//String code =  "011joAuv0Ylkti1uhquv0K3ouv0joAuA";
	    	String appId = "wx1be1cc389e8dffb9";
	    	String secret = "2a0f980625458e10644c351b96230e99";
	    	//String url2 = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
	    	String url2 = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appId+"&secret="+secret+"&code="+code+"&grant_type=authorization_code";
	    	
	         URL url = new URL(url2);
	         HttpURLConnection con = (HttpURLConnection) url.openConnection();
	         con.setDoOutput(true); //获取返回数据需要设置为true 默认false
	         con.setDoInput(true); //发送数据需要设置为true 默认false
	         con.setReadTimeout(5000);
	         con.setConnectTimeout(5000);
	         con.setRequestMethod("GET");
	         con.connect();
	         DataOutputStream out = new DataOutputStream(con.getOutputStream());
	         out.flush();
	         out.close();
	         BufferedReader red = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"));
	         StringBuffer sb = new StringBuffer();
	         String line;
	         while ((line = red.readLine()) != null) {
	              sb.append(line);
	         }
	         System.out.println(sb.toString());
	         red.close();
	         
	         Map map = (Map)JSON.parse(sb.toString());
	         String newopenid=(String)map.get("openid");
	 		Map<String,Object> paramMap=new HashMap<String,Object>();
			paramMap.put("userOpenid", newopenid);
			paramMap.put("mechId", "2");
			User user=userService.getBy(paramMap);
			Map<String,Object> paramMapp=new HashMap<String,Object>();
			paramMapp.put("userOpenid", state);
			paramMapp.put("mechId", "2");
			User userp=userService.getBy(paramMapp);
			
			System.out.println(user+":"+userp);
			if(user == null) {
				//创建base用户
				User cultureUser=new User();
				cultureUser.setUserOpenid(newopenid);
				cultureUser.setMechId("2");
				cultureUser.setUserType("0");
				if(state!=null&&!state.equals(state)) {
					cultureUser.setParentUserId(userp.getId()+"");
				}
				cultureUser.setAddTime(new Date());
				baseUserPlusMapper.insertOne(cultureUser);
			}else {
				
				System.out.println(userp.getId().intValue()!=user.getId().intValue());
				System.out.println(userp.getId().intValue()+":"+user.getId().intValue());
				
				if(userp!=null&&userp.getId().intValue()!=user.getId().intValue()) {
					user.setParentUserId(userp.getId()+"");
					baseUserPlusMapper.updateOne(user);
				}
			}
	         return (Map)JSON.parse(sb.toString());
	    } catch (Exception e) {
	         e.printStackTrace();
	         return null;
	    }
	}

	public Map<String, Object> initUserInfo(String openid, String parent_openid) {
		// TODO Auto-generated method stub
		//查询分享记录是否存在
		Map<String, Object> restMap = new HashMap<String,Object>();
		if(StringUtils.isEmpty(openid)||"null".equals(openid)||"undefined".equals(openid)) {
			restMap.put("code", "0003");
			restMap.put("msg", "openid不能为空");
			return restMap;
		}
				Map<String,Object> paramMap=new HashMap<String,Object>();
				paramMap.put("userOpenid", openid);
				paramMap.put("mechId", "2");
				User user=userService.getBy(paramMap);
				User parentUser = null;
				if(StringUtils.isNotEmpty(parent_openid)) {
					paramMap.put("userOpenid", parent_openid);
					paramMap.put("mechId", "2");
					parentUser=userService.getBy(paramMap);
				}
				if(user == null) {
					//创建base用户
					User cultureUser=new User();
					cultureUser.setUserOpenid(openid);
					cultureUser.setMechId("2");
					cultureUser.setUserType("0");
					if(parentUser!=null) {
						cultureUser.setParentUserId(parentUser.getId()+"");
					}
					cultureUser.setAddTime(new Date());
					baseUserPlusMapper.insertOne(cultureUser);
					
					paramMap.put("userOpenid", openid);
					paramMap.put("mechId", "2");
					user=userService.getBy(paramMap);
					
					//创建分享记录
					UserShareLog cultureUserShareLog1=new UserShareLog();
					cultureUserShareLog1.setCreateTime(new Date());
					cultureUserShareLog1.setUserId(user.getId()+"");
					cultureUserShareLog1.setShareUrl("");
					cultureUserShareLog1.setCreateBy(user.getId()+"");
					cultureUserShareLog1.setCreateBy(cultureUser.getId()+"");
					cultureUserShareLog1.setReserveFields1("山河盛景,我为祖国点个赞!");
					cultureUserShareLogPlusMapper.insertOne(cultureUserShareLog1);

				}else{
					if(parentUser!=null) {
						user.setParentUserId(parentUser.getId()+"");
						baseUserPlusMapper.updateOne(user);
					}
				}
				restMap.put("code", "0000");
				restMap.put("msg", "初始化成功");
				return restMap;
		}
	
	}
